package com.zang;

/**
 * @Author: ZVerify
 * @Description: TODO
 * @DateTime: 2022/9/30 15:08
 **/
public class 在排序数组中查找元素的第一个和最后一个 {
    public static void main(String[] args) {
        在排序数组中查找元素的第一个和最后一个 在排序数组中查找元素的第一个和最后一个 = new 在排序数组中查找元素的第一个和最后一个();

        在排序数组中查找元素的第一个和最后一个.searchRange(new int[]{5, 7, 7, 8, 8, 10},8);
    }

    public  int[] searchRange(int[] nums, int target) {


        int leftBorder = getLeft(nums, target);
        int rightBorder = getRight(nums, target);

        if (leftBorder == -2 || rightBorder == -2) return new int[]{-1, -1};

        if (rightBorder - leftBorder > 1) return new int[]{leftBorder + 1, rightBorder - 1};

        return new int[]{-1, -1};

    }

    private int getLeft(int[] nums, int target){
        int leftBoard = -2;
        int left = 0;
        int right = nums.length-1;
        while (left<=right){
            int mid = left+(right-left)>>1;
            if (nums[mid]<target){
                left = mid+1;
            }else{
                right = mid-1;
                leftBoard = right;
            }
        }
        return leftBoard;

    }

    private int getRight(int[] nums, int target){
        int left = 0;
        int right = nums.length - 1;
        int rightBorder = -2; // 记录一下rightBorder没有被赋值的情况
        while (left <= right) {
            int middle = left + ((right - left) / 2);
            if (nums[middle] > target) {
                right = middle - 1;
            } else { // 寻找右边界，nums[middle] == target的时候更新left
                left = middle + 1;
                rightBorder = left;
            }
        }
        return rightBorder;
    }




}
